package com.ruimayi.sitemoney.VolleyUtils;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.ruimayi.sitemoney.app.MyApplication;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.util.Map;

public class HttpUtil {

    private static HttpUtil mHttpUtil;
    private Gson mGson;


    //连接超时时间
    private static final int REQUEST_TIMEOUT_TIME = 60 * 1000;

    //volley请求队列
    public static RequestQueue mRequestQueue;

    private HttpUtil() {
        mGson = new Gson();
        //这里使用Application创建全局的请求队列
        mRequestQueue = Volley.newRequestQueue(MyApplication.getAppContext());
    }

    public static HttpUtil getInstance() {
        if (mHttpUtil == null) {
            synchronized (HttpUtil.class) {
                if (mHttpUtil == null) {
                    mHttpUtil = new HttpUtil();
                }
            }
        }
        return mHttpUtil;
    }

    /**
     * http请求
     *
     * @param url          http地址（后缀）
     * @param param        参数
     * @param httpCallBack 回调
     */
    public <T> void request(String url, final Map<String, String> param, final HttpCallBack<T> httpCallBack) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST,   url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        if (httpCallBack == null) {
                            return;
                        }

                        Type type = getTType(httpCallBack.getClass());

                        HttpResult httpResult = mGson.fromJson(response, HttpResult.class);
                        if (httpResult != null) {
                            if (httpResult.getC() != 200) {//失败
                                httpCallBack.onFail(httpResult.getM());
                            } else {//成功
                                //获取data对应的json字符串
                                String json = mGson.toJson(httpResult.getD());
                                if (type == String.class) {//泛型是String，返回结果json字符串
                                    httpCallBack.onSuccess((T) json);
                                } else {//泛型是实体或者List<>
                                    T t = mGson.fromJson(json, type);
                                    httpCallBack.onSuccess(t);
                                }
                            }
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (httpCallBack == null) {
                    return;
                }
                String msg = error.getMessage();
                httpCallBack.onFail(msg);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                //请求参数
                return param;
            }

        };
        //设置请求超时和重试
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(REQUEST_TIMEOUT_TIME, 1, 1.0f));
        //加入到请求队列
        if (mRequestQueue != null)
            mRequestQueue.add(stringRequest.setTag(url));
    }


    //====================================Get================================
    /**
     * http请求
     *
     * @param urlAddress          http地址（后缀）
     * @param paramsMap        参数
     * @param httpCallBack 回调
     */
    public <T> void request_get(String urlAddress, final Map<String, String> paramsMap, final HttpCallBack<T> httpCallBack) {
        try {
            String baseUrl = urlAddress;
            StringBuilder tempParams = new StringBuilder();
            int pos = 0;
            for (String key : paramsMap.keySet()) {
                if (pos > 0) {
                    tempParams.append("&");
                }
                tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key), "utf-8")));
                pos++;
            }
            String requestUrl = baseUrl + tempParams.toString();
            Log.e("http_params","---------------requestUrl--------------:"+requestUrl);
            StringRequest stringRequest = new StringRequest(Request.Method.GET, requestUrl,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            if (httpCallBack == null) {
                                return;
                            }
                            Log.e("http_params","---------------requestUrl----------1----:");
                            Type type = getTType(httpCallBack.getClass());
                            Log.e("http_params","---------------requestUrl-----------response---:"+response);
                            HttpResult httpResult = mGson.fromJson(response, HttpResult.class);
                            if (httpResult != null) {
                                if (httpResult.getC() != 200) {//失败
                                    httpCallBack.onFail(httpResult.getM());
                                } else {//成功
                                    //获取data对应的json字符串
                                    String json = mGson.toJson(httpResult.getD());
                                    if (type == String.class) {//泛型是String，返回结果json字符串
                                        httpCallBack.onSuccess((T) json);
                                    } else {//泛型是实体或者List<>
                                        T t = mGson.fromJson(json, type);
                                        httpCallBack.onSuccess(t);
                                    }
                                }
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if (httpCallBack == null) {
                        return;
                    }
                    Log.e("http_params","---------------requestUrl------error--------:"+error.getMessage());
                    String msg = error.getMessage();
                    httpCallBack.onFail(msg);
                }
            });
            //设置请求超时和重试
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(REQUEST_TIMEOUT_TIME, 1, 1.0f));
            //加入到请求队列
            if (mRequestQueue != null) {
                mRequestQueue.add(stringRequest);
            }
        }catch (Exception e){
            if (httpCallBack == null) {
                return;
            }
            Log.e("http_params","---------------requestUrl------Exception--------:"+e.getMessage());
            String msg = "数据异常";
            if (httpCallBack != null) {
                httpCallBack.onFail(msg);
            }
        }
    }




    private Type getTType(Class<?> clazz) {
        Type mySuperClassType = clazz.getGenericSuperclass();
        Type[] types = ((ParameterizedType) mySuperClassType).getActualTypeArguments();
        if (types != null && types.length > 0) {
            //T
            return types[0];
        }
        return null;
        }
}